package com.huarui.company.action;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.ewaf.framework.action.BaseAction;
import org.ewaf.framework.struts2.util.DateFormatUtil;

import com.huarui.company.model.Company;
import com.huarui.company.model.RegisterInvitation;
import com.huarui.company.service.CompanyService;
import com.huarui.company.service.InvitationService;
import com.huarui.company.util.JoinStringUtil;
import com.huarui.employee.model.AddingEmployee;
import com.huarui.employee.model.Employee;
import com.huarui.employee.service.AddingEmployeeService;
import com.huarui.employee.service.EmployeeService;
import com.huarui.user.model.SessionMessage;
import com.huarui.user.model.User;
import com.huarui.user.security.UserHolder;
import com.huarui.user.service.UserService;

public class InviteAction extends BaseAction {
	private static final long serialVersionUID = 2585980576848465721L;
	private Integer invitorId;// 邀请者ID（用户表中的ID）
	private String acceptEmail;// 被邀请者email
	private String invitorName;// 邀请者名字
	private String employeeEmail;// 邀请加入的员工Email
	private Integer companyId;
	private CompanyService companyService;
	private InvitationService invitationService;
	private EmployeeService employeeService;
	private UserService userService;
	private Map<String, Object> resultMap = new HashMap<String, Object>();
    private AddingEmployeeService addingEmployeeService;
    
    
    
	public Map<String, Object> getResultMap() {
		return resultMap;
	}

	public String getInvitorName() {
		return invitorName;
	}

	public void setInvitorName(String invitorName) {
		this.invitorName = invitorName;
	}

	public void setAddingEmployeeService(AddingEmployeeService addingEmployeeService) {
		this.addingEmployeeService = addingEmployeeService;
	}

	public Integer getInvitorId() {
		return invitorId;
	}

	public void setInvitorId(Integer invitorId) {
		this.invitorId = invitorId;
	}

	public Integer getCompanyId() {
		return companyId;
	}

	public void setCompanyId(Integer companyId) {
		this.companyId = companyId;
	}

	public String getAcceptEmail() {
		return acceptEmail;
	}

	public void setAcceptEmail(String acceptEmail) {
		this.acceptEmail = acceptEmail;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public CompanyService getCompanyService() {
		return companyService;
	}

	public void setCompanyService(CompanyService companyService) {
		this.companyService = companyService;
	}

	public InvitationService getInvitationService() {
		return invitationService;
	}

	public void setInvitationService(InvitationService invitationService) {
		this.invitationService = invitationService;
	}

	public String getEmployeeEmail() {
		return employeeEmail;
	}

	public void setEmployeeEmail(String employeeEmail) {
		this.employeeEmail = employeeEmail;
	}

	public EmployeeService getEmployeeService() {
		return employeeService;
	}

	public void setEmployeeService(EmployeeService employeeService) {
		this.employeeService = employeeService;
	}

	/**
	 * 显示邀请公司注册页面
	 * 
	 * @return
	 */
	public String toCompanyInvite() {
		return "toCompanyInvite";
	}

	/**
	 * 显示邀请员工加入页面
	 */
	public String toEmployeeInvite() {
		SessionMessage message = UserHolder.getCurrentSessionMessage();
		invitorId = message.getUserId();
		invitorName = message.getUserName();
		companyId = message.getCompanyId();
		return "toEmployeeInvite";
	}

	/**
	 * 
	 * 发送公司注册邀请
	 * 
	 * @return
	 * @throws Exception
	 */
	public String invite() throws Exception {
		SessionMessage message = UserHolder.getCurrentSessionMessage();
		invitorId = message.getUserId();
		invitorName = message.getUserName();
		RegisterInvitation inviteRegister = new RegisterInvitation();
		inviteRegister.setEmail(acceptEmail);
		inviteRegister.setInvitorId(invitorId);
		try {
			invitationService.create(inviteRegister);
			invitationService.sendRegisterInvitation(acceptEmail, invitorName,
					inviteRegister.getId());
		} catch (Exception e) {

			resultMap.put("failure", e.getMessage());

			return "json";
		}
		resultMap.put("success", "OK");
		return "json";
	}

	/**
	 * 发送员工加入公司邀请
	 * 
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public String empInvite() throws Exception {
		SessionMessage message = UserHolder.getCurrentSessionMessage();
		Integer creatorId = message.getUserId();
		String creatorName = message.getUserName();
		Integer companyId = message.getCompanyId();
		
		String jsonAll = httpServletRequest.getParameter("jsonAll");
		
		JSONObject jsonObject =  JSONObject.fromObject(jsonAll);
		
		String email=jsonObject.getString("email");
		
		String employeeId=jsonObject.getString("id");
		
		Integer id=null;
		
		if(StringUtils.isNotBlank(employeeId)){
			
			id=Integer.valueOf(employeeId);
			
		}
		
		User user = userService.getUserByEmail(email);
		
		Company company = (Company)companyService.getById(companyId);	
		
		Map map = new HashMap();
		
		map.put("companyId",companyId);
		map.put("addeeEmail", email);
		
		AddingEmployee addingEmployee =  addingEmployeeService.getByEmailAndCompanyId(map);
		//随机生成密码
		String password = JoinStringUtil.getCode();
		
		
		// 员工未注册，发送注册邮件
		if (user == null) {
			// 发送加入公司邀请
			if(addingEmployee!=null){
										
				 addingEmployee=getNewAddingEmployee(addingEmployee,jsonObject);
				
				 String over=isUserCode(addingEmployee,companyId,id);
			        
				 if(StringUtils.isNotBlank(over)){
					 
					    resultMap.put("failure", "该员工工号已被使用");				    
						return "json";
				} 
				addingEmployeeService.update(addingEmployee);
				invitationService.sendEmpInvitation(addingEmployee,addingEmployee.getPassword(),false);
				
			}else{

				try {
					addingEmployee=getAddingEmployee(creatorId,creatorName,company,null,jsonObject,password);
					
					 String over=isUserCode(addingEmployee,companyId,id);
				        
					 if(StringUtils.isNotBlank(over)){
						
						    resultMap.put("failure", "该员工工号已被使用");					    
							return "json";
					} 
					
					addingEmployeeService.create(addingEmployee);
					invitationService.sendEmpInvitation(addingEmployee,addingEmployee.getPassword(),false);
				} catch (Exception e) {
				
					e.printStackTrace();
				}
				
			}
			resultMap.put("success", "OK");
			return "json";

		}
		// 已是某公司员工不能重复加入
		if (user.getCompanyId() != 0&&user.getCompanyId()!=null) {
                 
			    if(user.getCompanyId().equals(company.getId())){
			    	
			    	resultMap.put("failure", "该用户已经是您公司的员工");
			    		    	
			    }else{
			    	
			    	resultMap.put("failure", "该用户已经是其他公司员工");
			    }
			

			return "json";

		} else if ("0".equals(user.getStatus())) {
			// 用户未激活

			resultMap.put("failure", "该用户还未激活");

			return "json";

		} else {
			// 发送加入公司邀请
			try {
						
				if(addingEmployee!=null){
					addingEmployee=getNewAddingEmployee(addingEmployee,jsonObject);
					
					 String over=isUserCode(addingEmployee,companyId,id);
				        
					 if(StringUtils.isNotBlank(over)){
						
						    resultMap.put("failure", "该员工工号已被使用");						    
							return "json";
						
					} 
					addingEmployeeService.update(addingEmployee);
					invitationService.sendEmpInvitation(addingEmployee,null,true);
					
				}else{

					try {
						//此时传入的密码并没有实际的什么作用,但由于数据库的password字段不允许为空,所以传入一个无效值
						 addingEmployee=getAddingEmployee(creatorId,creatorName,company,user.getId(),jsonObject,password);

						 String over=isUserCode(addingEmployee,companyId,id);
				        
						 if(StringUtils.isNotBlank(over)){
							
								
						    resultMap.put("failure", "该员工工号已被使用");
							return "json";
							
						} 
						 
						addingEmployeeService.create(addingEmployee);
						
						invitationService.sendEmpInvitation(addingEmployee,null,true);
					} catch (Exception e) {
						
						e.printStackTrace();
					}
					
				} 
				
				
			} catch (Exception e) {

				resultMap.put("failure", "发送邀请邮件失败,可能因为网络原因,请再次发送,如还不行,请立即与我们客服联系");

				return "json";

			}
			
			resultMap.put("success", "OK");
			return "json";
		}
	}
	
	private AddingEmployee getAddingEmployee(Integer creatorId,String creatorName,Company company,Integer userId, JSONObject jsonObject,String password){
		String addeeEmail=jsonObject.getString("email");
		String code = jsonObject.getString("code");
		String memo = jsonObject.getString("memo");
		String departmentId = jsonObject.getString("departmentId");
		String name = jsonObject.getString("name");
		String gmtHire =jsonObject.getString("gmtHire");
		
		
		AddingEmployee addingEmployee = new AddingEmployee();
		addingEmployee.setActivateCode(UUID.randomUUID().toString());
		addingEmployee.setAddeeEmail(addeeEmail);
		addingEmployee.setCreatorId(creatorId);
		addingEmployee.setCreatorName(creatorName);
		addingEmployee.setCompanyName(company.getName());
		addingEmployee.setCompanyId(company.getId());
		if(StringUtils.isNotBlank(departmentId)){
			
			addingEmployee.setDepartmentId(Integer.valueOf(departmentId));
		}
		if(userId!=null){
		addingEmployee.setAddeeId(userId);
		}
		addingEmployee.setMemo(memo);
		addingEmployee.setAddeeEmail(addeeEmail);
		
		if(StringUtils.isNotBlank(gmtHire)){
			
			 addingEmployee.setGmtHire(DateFormatUtil.parseDate(gmtHire));
		}
		
       
        addingEmployee.setName(name);
        addingEmployee.setCode(code);
        addingEmployee.setPassword(password);
        return addingEmployee;
        
	}
	
	private AddingEmployee getNewAddingEmployee(AddingEmployee addingEmployee,JSONObject jsonObject){
		
		String code = jsonObject.getString("code");
		String memo = jsonObject.getString("memo");
		String departmentId = jsonObject.getString("departmentId");
		String name = jsonObject.getString("name");
		String gmtHire =jsonObject.getString("gmtHire");
		if(StringUtils.isNotBlank(departmentId)){
			
			addingEmployee.setDepartmentId(Integer.valueOf(departmentId));
		}
		if(StringUtils.isNotBlank(gmtHire)){
			
			 addingEmployee.setGmtHire(DateFormatUtil.parseDate(gmtHire));
		}
		
	   addingEmployee.setActivateCode(UUID.randomUUID().toString());
	   addingEmployee.setMemo(memo);
       addingEmployee.setName(name);
       addingEmployee.setCode(code);
       
       return  addingEmployee;
	}
	
	@SuppressWarnings("unchecked")
	private String isUserCode(AddingEmployee addingEmployee,Integer companyId,Integer id){
		
		 if(StringUtils.isNotBlank(addingEmployee.getCode())){
				Map m = new HashMap();
				
		        m.put("companyId",companyId);
		        m.put("code",addingEmployee.getCode());
							
				Employee  e= employeeService.getEmployeeByCodeAndCompanyId(m);
				
				if(e!=null){
                    if(id==null){
                    	
                    	return "json";
                    	
                    }else{
                    	
                      if(!id.equals(e.getId()))
                    		
	    			  return "json";
	    			
                    }
					
				}		
			}
		 
		 return "";
		
	}
}
